import '../css/styles.css';

document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const response = await fetch(getApiUrl('login'), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.message || '登录失败');
        }

        // 保存用户信息和token到localStorage
        localStorage.setItem('user', JSON.stringify(data.user));
        localStorage.setItem('token', data.token);

        // 如果是管理员，跳转到软件列表页面
        if (data.user.role === 'admin') {
            window.location.href = 'index.html';
        } else {
            showAlert('只有管理员可以登录系统', 'error');
        }
    } catch (error) {
        console.error('登录错误:', error);
        showAlert(error.message || '登录失败，请重试', 'error');
    }
});

function showAlert(message, type, duration = 3000) {
    const alertBox = document.getElementById('alertBox');
    if (!alertBox) return;
    
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type}`;
    
    requestAnimationFrame(() => {
        alertBox.classList.add('show');
    });
    
    if (alertBox.hideTimeout) {
        clearTimeout(alertBox.hideTimeout);
    }
    
    alertBox.hideTimeout = setTimeout(() => {
        alertBox.classList.remove('show');
    }, duration);
} 